﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ModalDownload.Models;
using WebMatrix.WebData;
using System.Web.Security;
using System.Data;
using System.IO;

namespace ModalDownload.Controllers
{
    public class AdminController : Controller
    {
        public ActionResult Index()
        {
            if (Request.IsAuthenticated)
                return View();
            return RedirectToAction("Login", "Admin");
        }
        public ActionResult Login()
        {
            return View("Login");
        }
        [HttpPost]
        public ActionResult Login(AdminLoginModel model)
        {
            if (string.IsNullOrEmpty(model.UserName)||string.IsNullOrEmpty(model.Password)){
                return View();
            }
            if (AdminLoginModel.Login(model))
            {
                FormsAuthentication.SetAuthCookie(model.UserName, true);
                return RedirectToAction("Index", "Admin");
            }
            return View(model);
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Login", "Admin");
        }

        public ActionResult ManageClass()
        {
            if (!Request.IsAuthenticated)
                return RedirectToAction("Login", "Admin");

            return View();
        }

        public JsonResult GetAllTypes(string mid)
        {
            ClassTable ct = null;
            if (!string.IsNullOrEmpty(mid))
            {
                ct = ClassTable.GetClassByID(ModelTable.GetModel(mid).classid.ToString());
            }
            List<SelectListItem> items = ClassTable.GetAllTypes();
            if (ct != null)
                foreach (SelectListItem item in items)
                    if (ct.type == item.Value)
                    {
                        item.Selected = true;
                        break;
                    }
            JsonResult J = new JsonResult();
            J.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            J.Data = items;
            return J;
        }

        public JsonResult GetParentClass(string type,string mid)
        {
            JsonResult J = new JsonResult();
            J.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            List<ClassTable> list = ClassTable.GetAllParentClass(type);
            List<SelectListItem> items = new List<SelectListItem>();
            ClassTable pct=null;
            if (!string.IsNullOrEmpty(mid)){
                pct =ClassTable.GetClassByID(ClassTable.GetClassByID(ModelTable.GetModel(mid).classid.ToString()).parentid.ToString());
            }
            foreach (ClassTable ct in list)
            {
                if (pct == null)
                    items.Add(new SelectListItem() { Text = ct.classname, Value = ct.ID.ToString() });
                else
                    items.Add(new SelectListItem() { Text = ct.classname, Value = ct.ID.ToString(),Selected=(pct.ID==ct.ID) });
            }
            J.Data = items;
            return J;
        }

        public JsonResult GetChildClass(string id,string mid)
        {
            JsonResult J = new JsonResult();
            J.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            List<ClassTable> list = ClassTable.GetAllClassByParent(int.Parse(id));
            List<SelectListItem> items = new List<SelectListItem>();
            ClassTable cct = null;
            if (!string.IsNullOrEmpty(mid))
            {
                cct = ClassTable.GetClassByID(ModelTable.GetModel(mid).classid.ToString());
            }
            foreach (ClassTable ct in list)
            {
                if (cct == null)
                    items.Add(new SelectListItem() { Text = ct.classname, Value = ct.ID.ToString() });
                else
                    items.Add(new SelectListItem() { Text = ct.classname, Value = ct.ID.ToString(), Selected = (cct.ID == ct.ID) });
            }
            J.Data = items;
            return J;
        }

        public ActionResult Publish(string viewmode,string id)
        {
            if (!Request.IsAuthenticated)
                return RedirectToAction("Login", "Admin");

            if (string.IsNullOrEmpty(viewmode))
                viewmode = "view";
            ViewBag.ID = id;
            ViewBag.ViewMode = viewmode;
            if (viewmode == "view" || viewmode == "edit")
            {
                ModelTable model = ModelTable.GetModel(id);
                return View(model);
            }
            else if (viewmode == "delete")
            {
                ModelTable model = ModelTable.GetModel(id);
                model.Delete();
                return RedirectToAction("ModelList", "Admin");
            }
            return View();
        }

        [HttpPost]
        public ActionResult Publish(ModelTable model,string viewmode)
        {
            if (Request.Files.Count == 0)
            {
                return RedirectToAction("Publish", "Admin");
            }

            int cid = 0;
            int.TryParse(Request.Form["child"],out cid);
            if (cid == 0)
            {
                return RedirectToAction("Publish", "Admin");
            }
            var c = Request.Files[0];
            if (c != null && c.ContentLength > 0)
            {
                int lastSlashIndex = c.FileName.LastIndexOf("\\");
                string fileName = c.FileName.Substring(lastSlashIndex + 1, c.FileName.Length - lastSlashIndex - 1);
                int pos=fileName.LastIndexOf('.');
                if(pos<=0)
                    return RedirectToAction("Publish", "Admin");
                string path = Path.Combine(System.IO.Path.GetDirectoryName(Request.PhysicalApplicationPath),"Images/Upload/");
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                model.imagefilename = System.Guid.NewGuid().ToString() + fileName.Substring(pos);
                fileName = Path.Combine(path, model.imagefilename);
                c.SaveAs(fileName);
            }

            model.classid = cid;
            model.Save(viewmode);
            return RedirectToAction("Publish", "Admin");
        }
        [ValidateInput(false)]
        public ActionResult WebSetting()
        {
            if (Request.HttpMethod == "POST")
            {
                if (Request.Form.AllKeys.Contains("sitename") && Request.Form.AllKeys.Contains("siteurl") && Request.Form.AllKeys.Contains("icp") && Request.Form.AllKeys.Contains("notice"))
                {
                    SQL_MS.ExecuteNonQuery("update settings set value='" + Request.Form["sitename"] + "' where [key]='sitename'", CommandType.Text, null);
                    SQL_MS.ExecuteNonQuery("update settings set value='" + Request.Form["siteurl"] + "' where [key]='siteurl'", CommandType.Text, null);
                    SQL_MS.ExecuteNonQuery("update settings set value='" + Request.Form["icp"] + "' where [key]='icp'", CommandType.Text, null);
                    SQL_MS.ExecuteNonQuery("update settings set value='" + Request.Form["notice"] + "' where [key]='notice'", CommandType.Text, null);
                }
            }
            HomeController.GetWebSettings(ViewData);
            return View();
        }

        public ActionResult ModelList(string type,string page)
        {
            ViewData["class"] = ClassTable.GetAllTypes();
            if (Request.HttpMethod == "POST")
            {
                type = Request.Form["class"];
            }
            if (string.IsNullOrEmpty(type))
                type = "3d";
            int p = 0;
            int.TryParse(page, out p);
            if (p <= 0)
                p = 1;
            ViewBag.Type = type;
            ViewBag.Total = ModelTable.GetTotal(type);
            ViewBag.Page = p;
            ViewBag.PageSize = 10;
            ViewBag.PageLength = Math.Ceiling((decimal)ViewBag.Total / ViewBag.PageSize);
            return View();
        }

        public ActionResult ManageAD(string page)
        {
            int p = 0;
            int.TryParse(page, out p);
            if (p <= 0)
                p = 1;
            ViewBag.Total = ADTable.GetTotal();
            ViewBag.Page = p;
            ViewBag.PageSize = 10;
            ViewBag.PageLength = Math.Ceiling((decimal)ViewBag.Total / ViewBag.PageSize);
            return View();
        }

        public ActionResult ADDetail(string viewmode,string id)
        {
            ADTable model = ADTable.GetModel(id);
            ViewBag.ViewMode = viewmode;
            return View(model);
        }

        [HttpPost]
        public ActionResult ADDetail(ADTable model, string viewmode)
        {
            model.Save(viewmode);
            ViewBag.ViewMode = viewmode;
            return View(model);
        }
    }
}
